import { Component, Output, EventEmitter, ViewChild } from '@angular/core';

import { FormBuilder, FormControl, FormGroup, ValidationErrors, Validators } from '@angular/forms';
import { Observable, Observer } from 'rxjs';
import { UserService } from '../user.service';
@Component({
  selector: 'app-add-form',
  templateUrl: './add-form.component.html',

  styleUrls: ['./add-form.component.css']
})
export class AddFormComponent {
  validateForm: FormGroup;

  buttonName = "确认添加"

  //当前被编辑的用户的id
  editUserId: string = "";

  @Output() noShowModel = new EventEmitter();

  @ViewChild('radio') radio: any;

  //添加或修改用户
  addOrEditUser(e: MouseEvent): void {
    if (this.buttonName == "确认添加") {
      this.userService.addUser(this.validateForm.controls.userName.value,
        this.validateForm.controls.number.value, this.validateForm.controls.password.value,
        this.radio.radioValue);
      this.noShowModel.emit();
      // this.resetForm(e);
      this.validateForm.reset();
      this.radio.setRadioValue("激活");
      console.log("radio选中的是:" + this.radio.radioValue);
    } else {
      this.userService.editUser(this.editUserId, this.validateForm.controls.userName.value,
        this.validateForm.controls.number.value, this.validateForm.controls.password.value,
        this.radio.radioValue);
      this.noShowModel.emit();
      // this.resetForm(e);
      this.validateForm.reset();
      this.radio.setRadioValue("激活");

    }
  }

  //修改用户时设初值
  setEditingUser(id: string) {
    this.editUserId = id;
    const editingUser = this.userService.listOfData[this.userService.listOfData.findIndex(function (item) {
      return item.id === id;
    })];
    this.validateForm.controls.userName.setValue(editingUser.name);
    this.validateForm.controls.number.setValue(editingUser.number);
    this.validateForm.controls.password.setValue(editingUser.password);
    this.validateForm.controls.confirm.setValue(editingUser.password);
    this.radio.setRadioValue(editingUser.status);
  }

  resetForm(e: MouseEvent): void {
    e.preventDefault();
    this.validateForm.reset();
    for (const key in this.validateForm.controls) {
      this.validateForm.controls[key].markAsPristine();
      this.validateForm.controls[key].updateValueAndValidity();
    }
    this.radio.setRadioValue("激活");
  }

  validateConfirmPassword(): void {
    setTimeout(() => this.validateForm.controls.confirm.updateValueAndValidity());
  }

  userNameAsyncValidator = (control: FormControl) =>
    new Observable((observer: Observer<ValidationErrors | null>) => {
      setTimeout(() => {
        if (control.value === 'JasonWood') {
          // you have to return `{error: true}` to mark it as an error event
          observer.next({ error: true, duplicated: true });
        } else {
          observer.next(null);
        }
        observer.complete();
        // 下面这行如果是这样，输入之后会等待1秒     }, 1000);
      });
    });

  numberAsyncValidator = (control: FormControl) =>
    new Observable((observer: Observer<ValidationErrors | null>) => {
      setTimeout(() => {
        if (control.value === 'JasonWood') {
          // you have to return `{error: true}` to mark it as an error event
          observer.next({ error: true, duplicated: true });
        } else {
          observer.next(null);
        }
        observer.complete();
      });
    });

  confirmValidator = (control: FormControl): { [s: string]: boolean } => {
    if (!control.value) {
      return { error: true, required: true };
    } else if (control.value !== this.validateForm.controls.password.value) {
      return { confirm: true, error: true };
    }
    return {};
  };

  constructor(private fb: FormBuilder, private userService: UserService) {
    this.validateForm = this.fb.group({
      userName: ['', [Validators.required], [this.userNameAsyncValidator]],
      number: ['', [Validators.required], [this.numberAsyncValidator]],
      password: ['', [Validators.required]],
      confirm: ['', [this.confirmValidator]],
    });
  }
  //在<form nz-form [formGroup]="validateForm" (ngSubmit)="submitForm(validateForm.value)">
  //表示点击提交后 再验证信息的其他符合度，如去数据库中验证用户名是否存在
  // submitForm(value: { userName: string; number: string; password: string; confirm: string; }): void {
  //   for (const key in this.validateForm.controls) {
  //     this.validateForm.controls[key].markAsDirty();
  //     this.validateForm.controls[key].updateValueAndValidity();
  //   }
  //   console.log(value);
  // }

}